package controller

import (
	"agent-list---web-development/list/common"
	"agent-list---web-development/list/model"
	"agent-list---web-development/list/response"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

// ShowTaskByDay 按日查看
func ShowTaskByDay(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.PostForm("account")
	day := time.Now() // 获取当前时间
	start := time.Date(day.Year(), day.Month(), day.Day(), 00, 00, 00, 999999999, time.Local)
	end := time.Date(day.Year(), day.Month(), day.Day(), 23, 59, 59, 999999999, time.Local)

	var task []model.Task
	err := DB.Where("account=? AND starttime<? AND endtime>?", account, end, start).Find(&task).Error // 使用 Unix 时间戳的纳秒表示来检索指定日期内的任务
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err)
		return
	}
	response.Success(ctx, gin.H{"task": task}, "获取成功")
}

// 按周查看
func ShowTaskByWeek(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.PostForm("account")
	now := time.Now()
	weekday := now.Weekday()
	start := now.AddDate(0, 0, -int(weekday)+1).Truncate(24 * time.Hour)
	end := start.AddDate(0, 0, 7).Add(-time.Second)
	var task []model.Task
	err := DB.Where("account=? AND starttime<? AND endtime>?", account, end, start).Find(&task).Error // 使用 Unix 时间戳的纳秒表示来检索指定日期内的任务
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err)
		return
	}
	response.Success(ctx, gin.H{"task": task}, "获取成功")
}

// ShowTaskByMonth 按月查看
func ShowTaskByMonth(ctx *gin.Context) {
	account := ctx.PostForm("account")
	DB := common.GetDB()
	now := time.Now()
	year, month, _ := now.Date()
	start := time.Date(year, month, 1, 0, 0, 0, 0, now.Location())
	end := start.AddDate(0, 1, -1).Add(24*time.Hour - time.Second)
	var task []model.Task
	err := DB.Where("account=? AND starttime<? AND endtime>?", account, end, start).Find(&task).Error // 使用 Unix 时间戳的纳秒表示来检索指定日期内的任务
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err)
		return
	}
	response.Success(ctx, gin.H{"task": task}, "获取成功")
}
